package com.supply.dl.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.supply.dl.R;
import com.supply.dl.activity.seachmode.ISearchModle;
import com.supply.dl.app.ApiService;
import com.supply.dl.app.AppConfig;
import com.supply.dl.app.adapter.NormalAdapter;
import com.supply.dl.app.adapter.RecyclerViewDivider;
import com.supply.dl.app.adapter.ViewHolder;
import com.supply.dl.app.http.BaseInfo;
import com.supply.dl.app.http.HttpMethod;
import com.supply.dl.app.http.NormalObserver;
import com.supply.dl.app.http.RxSchedulers;
import com.supply.dl.bean.FilterMapBean;
import com.supply.dl.bean.FilterParentBean;
import com.supply.dl.bean.SelectDictionaryBean;
import com.supply.dl.constant.Constants;
import com.supply.dl.utils.DateUtils;
import com.supply.dl.utils.StringUtils;
import com.supply.dl.widget.LoadTipFailedLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function3;

/**
 * Created by Leng on 2018/9/5.
 */
public class FilterActvity extends Activity {

    /**
     * 筛选rv
     */
    @BindView(R.id.filter_rvs)
    RecyclerView filterRv;


    /**
     * 没有数据时 见到的视图
     */
    @BindView(R.id.inbound_location_main_loadView)
    LoadTipFailedLayout inbound_location_main_loadView;



    /**
     * 建单结束时间
     */
    @BindView(R.id.end_time_tv)
    TextView end_time_tv;

    /**
     * 建单起点时间
     */
    @BindView(R.id.start_time_tv)
    TextView start_time_tv;

    /**
     * 建单时间title
     */
    @BindView(R.id.activity_search_tvCreateTimeTitle)
    TextView tvCreateTimeTitle;

    /**
     * 建单时间布局
     */
    @BindView(R.id.create_time_ly)
    RelativeLayout create_time_ly;

    /**
     * 预约时间title
     */
    @BindView(R.id.activity_search_tvReservateTimeTitle)
    TextView tvReservateTimeTitle;

    /**
     * 预约时间布局
     */
    @BindView(R.id.reservate_time_ly)
    RelativeLayout reservate_time_ly;

    /**
     * 预约开始时间
     */
    @BindView(R.id.reservate_start_time_tv)
    TextView reservate_start_time_tv;

    /**
     * 预约结束时间
     */
    @BindView(R.id.reservate_end_time_tv)
    TextView reservate_end_time_tv;

    /**
     * 模块的名字
     */
    private String modleName;


    /**
     * 当前用户选择的 筛选条件
     */
    private Map<String, String> filerMaps = new HashMap<>();


    /**
     * 筛选列表适配器
     */
    private NormalAdapter<FilterParentBean> filterAdapter;

    /**
     * 筛选数据来源
     */
    private ArrayList<FilterParentBean> filterDatas;

    /**
     * 开始和时间pickerview
     */
    private TimePickerView startPicker, endPicker, resStartPicker, resEndPicker;

    int mActivityFlag = -1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.filter_activity);
        ButterKnife.bind(this);
        modleName = getIntent().getStringExtra("modelName");
        if (getIntent().hasExtra(Constants.FLAG_ACTIVITY_KEY)) {
            mActivityFlag = getIntent().getIntExtra(Constants.FLAG_ACTIVITY_KEY, -1);
        }
        loadFilterDataByModleName();
        initFilterLy();
    }

    /**
     * 初始化 筛选布局
     */
    private void initFilterLy() {

        filterDatas = new ArrayList<>();

        filterAdapter = new NormalAdapter<FilterParentBean>(this, filterDatas) {
            @Override
            protected void convert(ViewHolder holder, FilterParentBean data) {
                holder.setText(R.id.parent_name_tv, data.getName());
                RecyclerView item_filter_rv = holder.getView(R.id.item_filter_rv);
                final NormalAdapter<SelectDictionaryBean> itemAdapter = new NormalAdapter<SelectDictionaryBean>(FilterActvity.this, data.getItemDatas()) {
                    @Override
                    protected void convert(ViewHolder holder, SelectDictionaryBean data) {
                        TextView name_tv = holder.getView(R.id.item_filter_tv);
                        if (data.isChecked()) {
                            name_tv.setBackgroundResource(R.drawable.rectangle_stroke_blue_bg);
                            name_tv.setTextColor(getResources().getColor(R.color.blue));
                        } else {
                            name_tv.setBackgroundResource(R.drawable.rectangle_stroke_gray_bg);
                            name_tv.setTextColor(getResources().getColor(R.color.textColor));
                        }
                        holder.setText(R.id.item_filter_tv, data.getText());
                    }

                    @Override
                    protected int getItemLayoutId() {
                        return R.layout.item_filter_child;
                    }
                };

                itemAdapter.setOnItemClickListener(new OnItemClickListener<SelectDictionaryBean>() {
                    @Override
                    public void onItemClick(ViewHolder viewHolder, SelectDictionaryBean item, int position) {
                        item.setChecked(!item.isChecked());
                        itemAdapter.notifyDataSetChanged();
                    }
                });
                item_filter_rv.setLayoutManager(new GridLayoutManager(FilterActvity.this, 3));
                item_filter_rv.setAdapter(itemAdapter);
            }

            @Override
            protected int getItemLayoutId() {
                return R.layout.item_search_filter;
            }
        };
        filterRv.addItemDecoration(new RecyclerViewDivider(this, LinearLayoutManager.VERTICAL));
        filterRv.setLayoutManager(new LinearLayoutManager(this));
        filterRv.setAdapter(filterAdapter);
    }


    @OnClick({R.id.filter_backImg,  R.id.btn_sure, R.id.start_time_tv
            , R.id.end_time_tv, R.id.reservate_end_time_tv, R.id.reservate_start_time_tv, R.id.btn_reset})
    public void OnClic(View v) {
        switch (v.getId()) {
            case R.id.filter_backImg:
                finish();
                overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_from_right);
                break;
            case R.id.btn_sure: //确定
                colectFilters();
                break;
            case R.id.btn_reset:   //重置按钮
                //将数据变为 ，未选中状态
                for (FilterParentBean fp : filterDatas) {
                    for (SelectDictionaryBean sb : fp.getItemDatas()) {
                        if (sb.isChecked()) {
                            sb.setChecked(false);
                        }
                    }
                }
                start_time_tv.setText("");
                start_time_tv.setHint("选择开始时间");

                end_time_tv.setText("");
                end_time_tv.setHint("选择结束时间");
                filterAdapter.notifyDataSetChanged();
                break;
            case R.id.start_time_tv:
                if (startPicker == null)
                    startPicker = new TimePickerView.Builder(FilterActvity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            start_time_tv.setText(DateUtils.getNormalTime(date));
                        }
                    }).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                            .setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setTitleText("选择起点时间")//标题文字
                            .build();

                startPicker.show();
                break;
            case R.id.end_time_tv: //结束时间
                if (endPicker == null)
                    endPicker = new TimePickerView.Builder(FilterActvity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            end_time_tv.setText(DateUtils.getNormalTime(date));
                        }
                    }).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                            .setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setTitleText("选择终点时间")//标题文字
                            .build();

                endPicker.show();
                break;
            case R.id.reservate_start_time_tv:
                if (resStartPicker == null)
                    resStartPicker = new TimePickerView.Builder(FilterActvity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            reservate_start_time_tv.setText(DateUtils.getNormalTime(date));
                        }
                    }).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                            .setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setTitleText("选择起点时间")//标题文字
                            .build();

                resStartPicker.show();
                break;
            case R.id.reservate_end_time_tv:
                if (resEndPicker == null)
                    resEndPicker = new TimePickerView.Builder(FilterActvity.this, new TimePickerView.OnTimeSelectListener() {
                        @Override
                        public void onTimeSelect(Date date, View v) {
                            reservate_end_time_tv.setText(DateUtils.getNormalTime(date));
                        }
                    }).setType(TimePickerView.Type.YEAR_MONTH_DAY_HOUR_MIN)
                            .setCancelText("取消")//取消按钮文字
                            .setSubmitText("确定")//确认按钮文字
                            .setTitleText("选择起点时间")//标题文字
                            .build();
                resEndPicker.show();
                break;
        }
    }


    /**
     * 采集搜索条件
     */
    private void colectFilters() {
        //采集关键字
        //采集非时间条件
        for (FilterParentBean fp : filterDatas) {
            for (SelectDictionaryBean sb : fp.getItemDatas()) {
                if (sb.isChecked()) {
                    if (filerMaps.containsKey(fp.getName())) {
                        //先获取之前存的值
                        String temp = filerMaps.get(fp.getName());
                        temp = temp + "," + sb.getValue();
                        filerMaps.put(fp.getName(), temp);
                    } else {
                        filerMaps.put(fp.getName(), sb.getValue());
                    }
                }
            }
        }

        //采集时间条件
        if (StringUtils.isCanUse(start_time_tv.getText().toString()))
            filerMaps.put(AppConfig.SearchFilterAction.START_TIME, start_time_tv.getText().toString());

        if (StringUtils.isCanUse(end_time_tv.getText().toString()))
            filerMaps.put(AppConfig.SearchFilterAction.END_TIME, end_time_tv.getText().toString());

        if (StringUtils.isCanUse(reservate_start_time_tv.getText().toString()))
            filerMaps.put(AppConfig.SearchFilterAction.RES_START_TIME, reservate_start_time_tv.getText().toString());

        if (StringUtils.isCanUse(reservate_end_time_tv.getText().toString()))
            filerMaps.put(AppConfig.SearchFilterAction.RES_END_TIME, reservate_end_time_tv.getText().toString());

        Intent intent = getIntent();
        final FilterMapBean myMap = new FilterMapBean();
        myMap.setMap(filerMaps);
        Bundle bundle = new Bundle();
        bundle.putSerializable("filterResult", myMap);
        intent.putExtras(bundle);
        setResult(1, intent);
        finish();
    }



    /**
     * 根据modleName进行筛选条件的选择，视图的匹配
     */
    private void loadFilterDataByModleName() {
        tvCreateTimeTitle.setVisibility(View.GONE);
        create_time_ly.setVisibility(View.GONE);
        tvReservateTimeTitle.setVisibility(View.GONE);
        reservate_time_ly.setVisibility(View.GONE);
        if (modleName.contains("MoveHouseGoodsModle") || modleName.contains("TakeDeliveryModel") ||
                modleName.contains("ChangeAndGetGoodsModle")) {
            //移库发货,移库收货，移库收货确认
            loadMoveHouseFilters();
            tvCreateTimeTitle.setVisibility(View.VISIBLE);
            create_time_ly.setVisibility(View.VISIBLE);
        } else if (modleName.contains("PickBillListModle") || modleName.contains("PickBillSureWareHouseModle")
                || modleName.contains("PickSendGoodsModle") || modleName.contains("PickUpGoodsModle")
                || modleName.contains("PickCollectGoodSureModle") || modleName.contains("FeedOperationOrderModle")) {
            //领料单列表，领料定库,领料发货，领料收货，领料收货确认
            loadFactoryCompanyWorkShop();
            tvCreateTimeTitle.setVisibility(View.VISIBLE);
            create_time_ly.setVisibility(View.VISIBLE);
        } else if (modleName.contains("InAndOutBoundLocationModle")||modleName.contains("OrderInAndOutBoundModle")
                    ||modleName.contains("NoticeLetterInAndOutBoundModle")||modleName.contains("ReceivingAndSendGoodsConfirmModle")) {
            //出、入库定位列表，订单出入库列表，通知单出入库列表，发货确认、收货确认列表
            loadRuKuFilterDatas();
            if(modleName.contains("InAndOutBoundLocationModle")||modleName.contains("NoticeLetterInAndOutBoundModle")){
                tvCreateTimeTitle.setVisibility(View.VISIBLE);
                create_time_ly.setVisibility(View.VISIBLE);
                tvReservateTimeTitle.setVisibility(View.VISIBLE);
                reservate_time_ly.setVisibility(View.VISIBLE);
            }else if(modleName.contains("OrderInAndOutBoundModle")||modleName.contains("ReceivingAndSendGoodsConfirmModle")){
                tvCreateTimeTitle.setVisibility(View.VISIBLE);
                create_time_ly.setVisibility(View.VISIBLE);
            }

        }
    }


    /**
     * 获取入库筛选数据，入库状态，业务类型，公司，工厂，车间  5个数据
     */
    public void loadRuKuFilterDatas() {
        ArrayList<Observable<BaseInfo<List<SelectDictionaryBean>>>> observables = new ArrayList<>();
        //入库状态
        observables.add(getBaseData(AppConfig.BaseDataAction.STO_ASN_NOTICE_ORDER_ORDER_STATUS));
        //业务类型
        observables.add(getBaseData(AppConfig.BaseDataAction.STO_ASN_ORDER_BUSS_TYPE));
        //公司
        observables.add(getBaseData(AppConfig.BaseDataAction.Company));
        //工厂
        observables.add(getFactoryListObservable());
        //车间
        observables.add(getWorkShopList());

        Observable.zip(observables, new Function<Object[], List<FilterParentBean>>() {
            @Override
            public List<FilterParentBean> apply(Object[] objects) throws Exception {
                ArrayList<FilterParentBean> fpbs = new ArrayList<>();
                for (int i = 0; i < objects.length; i++) {
                    BaseInfo<List<SelectDictionaryBean>> item = (BaseInfo<List<SelectDictionaryBean>>) objects[i];
                    String key = "";
                    switch (i) {
                        case 0:
                            if(modleName.contains("InAndOutBoundLocationModle")){
                                key = "定库状态";
                            }else if( modleName.contains("NoticeLetterInAndOutBoundModle")||
                                    modleName.contains("ReceivingAndSendGoodsConfirmModle")){
                                key = "入库状态";
                            }else if(modleName.contains("OrderInAndOutBoundModle")){
                                if(mActivityFlag == Constants.FLAG_ACTIVITY_ORDER_IN_BOUND_UI){
                                    key = "订单状态";
                                }else{
                                    key = "出库状态";
                                }
                            }

                            break;
                        case 1:
                            key = "业务类型";
                            break;
                        case 2:
                            key = "公司";
                            break;
                        case 3:
                            key = "工厂";
                            break;
                        case 4:
                            key = "车间";
                            break;
                    }

                    if (StringUtils.isCanUse(key))
                        fpbs.add(new FilterParentBean(key, item.getData()));
                }
                return fpbs;
            }
        }).subscribe(new NormalObserver<List<FilterParentBean>>() {
            @Override
            public void onNext(List<FilterParentBean> data) {
                if (data != null || data.size() > 0) {
                    filterDatas.clear();
                    filterDatas.addAll(data);
                    filterAdapter.notifyDataSetChanged();
                }

            }
        });
    }

    /**
     * 获取 公司，工厂，车间的操作
     */
    public void loadFactoryCompanyWorkShop() {
        Observable.zip(getBaseData(AppConfig.BaseDataAction.Company),
                getFactoryListObservable(), getWorkShopList(),
                new Function3<BaseInfo<List<SelectDictionaryBean>>, BaseInfo<List<SelectDictionaryBean>>, BaseInfo<List<SelectDictionaryBean>>,
                                        List<FilterParentBean>>() {
                    @Override
                    public List<FilterParentBean> apply(BaseInfo<List<SelectDictionaryBean>> listBaseInfo, BaseInfo<List<SelectDictionaryBean>> listBaseInfo2,
                                                        BaseInfo<List<SelectDictionaryBean>> listBaseInfo3) throws Exception {
                        FilterParentBean fp1 = new FilterParentBean("公司", listBaseInfo.getData());
                        FilterParentBean fp2 = new FilterParentBean("工厂", listBaseInfo2.getData());
                        FilterParentBean fp3 = new FilterParentBean("车间", listBaseInfo3.getData());
                        ArrayList<FilterParentBean> fpDatas = new ArrayList<>();

                        fpDatas.add(fp1);
                        fpDatas.add(fp2);
                        fpDatas.add(fp3);

                        return fpDatas;
                    }
                }).subscribe(new NormalObserver<List<FilterParentBean>>() {
            @Override
            public void onNext(List<FilterParentBean> data) {
                if (data != null || data.size() > 0) {
                    filterDatas.clear();
                    filterDatas.addAll(data);
                    filterAdapter.notifyDataSetChanged();
                }
            }
        });

    }

    /**
     * 获取 移库订单类型和 移库订单状态的 操作
     */
    public void loadMoveHouseFilters() {
        Observable.zip(getBaseData(AppConfig.BaseDataAction.STO_TF_ORDER_ORDER_TYPE),
                getBaseData(AppConfig.BaseDataAction.STO_TF_ORDER_ORDER_DISPLAY_STATUS),
                new BiFunction<BaseInfo<List<SelectDictionaryBean>>, BaseInfo<List<SelectDictionaryBean>>, List<FilterParentBean>>() {
                    @Override
                    public List<FilterParentBean> apply(BaseInfo<List<SelectDictionaryBean>> listBaseInfo, BaseInfo<List<SelectDictionaryBean>> listBaseInfo2) throws Exception {
                        FilterParentBean fp1 = new FilterParentBean("移库订单类型", listBaseInfo.getData());
                        FilterParentBean fp2 = new FilterParentBean("移库订单状态", listBaseInfo2.getData());

                        ArrayList<FilterParentBean> fpDatas = new ArrayList<>();

                        fpDatas.add(fp1);
                        fpDatas.add(fp2);

                        return fpDatas;
                    }
                }).subscribe(new NormalObserver<List<FilterParentBean>>() {
            @Override
            public void onNext(List<FilterParentBean> data) {

                if (data != null || data.size() > 0) {
                    filterDatas.clear();
                    filterDatas.addAll(data);
                    filterAdapter.notifyDataSetChanged();
                }
            }
        });
    }







    /***-----------------------------------------------华丽丽的分割线下面部分全部是配置和条件接口---------------------------------------------------------------*/

    /**
     * 获取工厂查询的Observable
     *
     * @return
     */
    public Observable<BaseInfo<List<SelectDictionaryBean>>> getFactoryListObservable() {
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        return mApiService.getFactoryList()
                .compose(RxSchedulers.<BaseInfo<List<SelectDictionaryBean>>>compose(this));
    }

    /**
     * 获取车间查询Observable
     *
     * @return
     */
    public Observable<BaseInfo<List<SelectDictionaryBean>>> getWorkShopList() {
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        return mApiService.getWorkShopList()
                .compose(RxSchedulers.<BaseInfo<List<SelectDictionaryBean>>>compose(this));
    }

    /**
     * 获取仓库查询Observable
     *
     * @param type 0(入库)，1(出库)
     * @return
     */
    public Observable<BaseInfo<List<SelectDictionaryBean>>> getHouseList(int type) {
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        return mApiService.getHouseList(type)
                .compose(RxSchedulers.<BaseInfo<List<SelectDictionaryBean>>>compose(this));
    }

    /**
     * 获取规格查询的Observable
     *
     * @param skuId
     * @return
     */
    public Observable<BaseInfo<List<SelectDictionaryBean>>> getBasUnitList(String skuId) {
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        return mApiService.getBasUnitList(skuId)
                .compose(RxSchedulers.<BaseInfo<List<SelectDictionaryBean>>>compose(this));
    }

    /**
     * 基础数据的Observable
     *
     * @param action
     * @return
     */
    public Observable<BaseInfo<List<SelectDictionaryBean>>> getBaseData(String action) {
        ApiService mApiService = HttpMethod.getInstance().create(ApiService.class);
        return mApiService.getDictionaryList(action).compose(RxSchedulers.<BaseInfo<List<SelectDictionaryBean>>>compose(this));
    }

}
